﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.IO;

namespace ConfigPatch
{
    class Program
    {
        static void Main(string[] args)
        {
            if (args.Length < 2 || args.Contains("-?")) {
                Console.WriteLine("Friends Nearby Config Patch:");
                Console.WriteLine("  ConfigPatch.exe <config_with_values> <file_to_patch>");
                Console.WriteLine("");
                Console.WriteLine("<config_with_values> must have the following AppSettings");
                return;
            }

            string configFileName = args[0];
            var config = GetConfiguration(configFileName);

            // load file to be pathed
            string fileToPatch = args[1];
            var doc = GetFileToPatch(fileToPatch);
            
            new XmlMerger(Console.Out).MergeNode(config.DocumentElement, doc);

            Console.WriteLine("Finished.");

            doc.Save(fileToPatch);
        }

        private static XmlDocument GetFileToPatch(string path)
        {
            Console.WriteLine("Merging {0}", path);
            File.Copy(path, path + ".bak", true);
            var doc = new XmlDocument();
            doc.Load(path);
            return doc;
        }

        private static XmlDocument GetConfiguration(string path)
        {
            Console.WriteLine("using {0}.", path);
            var config = new XmlDocument();
            config.Load(path);
            Console.WriteLine("configuration loaded.");
            return config;
        }
    }
}
